import efinance as ef
import pandas as pd
import akshare as ak

# 获取全市场实时行情数据（包含市值）
quotes = ef.stock.get_realtime_quotes()

# 筛选所需字段并重命名列
selected_columns = {
    '股票代码': '代码',
    '股票名称': '股票名称',
    '最新价': '收盘价',
    '总市值': '市值(亿元)',
}
result = quotes[list(selected_columns.keys())].rename(columns=selected_columns)

# 格式化数据
result['市值(亿元)'] = (result['市值(亿元)'] / 1e8).round(2)  # 转换为亿元单位
result['收盘价'] = result['收盘价'].round(2)
def get_dividend_rate(code):
    """获取最新年报股息率"""
    # try:
    #     dividend_df = ak.stock_fhps_detail_em(symbol=code)
    #     return dividend_df['现金分红-股息率'].iloc[0]
    # except Exception as e:
    #     print(f"获取{code}股息率失败: {str(e)}")
    return 0.0  # 默认值
result['股息率'] = result['代码'].apply(get_dividend_rate)

# 保存数据
result.to_csv('A股今日行情.csv', encoding='utf-8-sig', index=False)
print(result.head(10))